import os
# import tushare as ts                # 股票数据
import tkinter as tk                # 界面库
from tkinter import ttk             # 界面库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg     # 和gui交互
from matplotlib.figure import Figure
# from matplotlib.pyplot import MultipleLocator                       # 
import matplotlib.ticker as ticker                                  # 设置刻度

# 计算标准差
# ======================================
def cacl_std(col):

    std5 = col.rolling(5).std()
    std10 = col.rolling(10).std()
    std20 = col.rolling(20).std()
    return std5[-1], std10[-1], std20[-1]

# ======================================

# 画图
# ======================================
def create_plot():
    cb1val = check_ma5.get()            # 获取ma5复选框
    cb2val = check_ma10.get()           # 获取ma10复选框
    cb3val = check_ma20.get()           # 获取ma20复选框
    # print(cb1val)

    e2val = e2.get()                    # 获取股票代码
    e3val = e3.get()                    # 获取开始时间
    e4val = e4.get()                    # 获取结束时间
    print(e2val)
    print(e3val)
    print(e4val)

    fig = Figure(figsize=(5, 4), dpi=100)           # 框  
    axc = fig.add_subplot(111)                      # 添加子图


    data = ts.get_hist_data(e2val, start = e3val, end = e4val)      # 通过API获取股票历史行情
    data = data.sort_index(ascending=True)                          # 正序

    # 在前面得到的子图上绘图
    axc.plot(data['close'])                                         # 画收盘价
    if cb1val == 1:                                                 # 根据复选框是否勾选画均线
        axc.plot(data['ma5'])
    if cb2val == 1:
        axc.plot(data['ma10'])
    if cb3val == 1:
        axc.plot(data['ma20'])

    axc.xaxis.set_major_locator(ticker.MultipleLocator(60))         # x轴坐标两个月间隔
    canvas = FigureCanvasTkAgg(fig, master=root)                    # 将绘制的图形显示到tkinter:创建属于root的canvas画布,并将图f置于画布上
    canvas.draw() 
    canvas.get_tk_widget().grid(row=0, column=3, rowspan=5, columnspan=3, padx=40, pady=15)       # 表格布局

    # 计算标准差，并放在Text框 
    std5, std10, std20 = cacl_std(data['close'])
    close = data['close'][-1]
    ma5 = data['ma5'][-1]
    ma10 = data['ma10'][-1]
    ma20 = data['ma20'][-1]

    p0 = "股票的收盘价为 %f" % (close)
    p1 = "股票的5天均价为 %f ,一个标准差的范围为(%f, %f)" % (ma5, ma5 - std5, ma5 + std5)
    p2 = "股票的10天均价为 %f ,一个标准差的范围为(%f, %f)" % (ma10, ma10 - std10, ma10 + std10)
    p3 = "股票的20天均价为 %f ,一个标准差的范围为(%f, %f)" % (ma20, ma20 - std20, ma20 + std20)

    flag = 0
    if close < ma5 - std5:
        flag = 1
        p4 = "股价在5天均价小于一个标准差"
    elif close > ma5 + std5 :
        flag = -1
        p4 = "股价在5天均价大于一个标准差"

    if close < ma10 - std10:
        flag = 1
        p4 = "股价在10天均价小于一个标准差"
    elif close > ma10 + std10 :
        flag = -1
        p4 = "股价在10天均价大于一个标准差"

    if close < ma20 - std20:
        flag = 1
        p4 = "股价在20天均价小于一个标准差"
    elif close > ma20 + std20 :
        flag = -1
        p4 = "股价在20天均价大于一个标准差"      

    if (len(p4) == 0):
        p5 = p0 + "\n" + p1 + "\n" + p2 + "\n" + p3 + "\n"
        text1.insert(tk.END, p5)
    else:
        p5 = p0 + "\n" + p1 + "\n" + p2 + "\n" + p3 + "\n" + p4
        text1.insert(tk.END, p5)

    if (flag == 0):
        label5['text'] = "按兵不动"
    elif (flag == -1):
        label5['text'] = "卖出"
    else:
        label5['text'] = "买入"

# ======================================

count = 2
while count:
    try:
        import tushare as ts
        print('已检测到tushare模块           ok')
        break
    except:
        print('检测到未安装tushare模块,现在开始安装......')
        os.system('pip install tushare -i https://pypi.tuna.tsinghua.edu.cn/simple')
        count -= 1
        continue

# ======================================

root=tk.Tk()
root.title("股票价格")
root.geometry('900x700')

# 各GUI组件设计

label1 = tk.Label(root, text="交易所")
label2 = tk.Label(root, text="股票代码")
label3 = tk.Label(root, text="起始日期")
label4 = tk.Label(root, text="结束日期")

cmb = ttk.Combobox(root)
cmb['value'] = ('上证所','深交所')
cmb.current(0)

e2 = tk.Entry(root)
e3 = tk.Entry(root)
e4 = tk.Entry(root)

check_ma5=tk.IntVar()
check_ma10=tk.IntVar()
check_ma20=tk.IntVar()

cb1 = tk.Checkbutton(root,text='MA5', variable = check_ma5)
cb2 = tk.Checkbutton(root,text='MA10', variable = check_ma10)
cb3 = tk.Checkbutton(root,text='MA20', variable = check_ma20)

button1 = tk.Button(root, text='运行', anchor='n', command = create_plot)


text1 = tk.Text(root, bg='white',width=75, height=8)
label5 = tk.Label(root, text="", width=8, height=8, fg='red', anchor='n', font=("黑体", 20, "normal")) # 

# 表格布局

label1.grid(row=0, column=0)
label2.grid(row=1, column=0)
label3.grid(row=2, column=0)
label4.grid(row=3, column=0)

cmb.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)

cb1.grid(row=4, column=0, columnspan=2)
cb2.grid(row=5, column=0, columnspan=2)
cb3.grid(row=6, column=0, columnspan=2)

button1.grid(row=8, column=0, columnspan=2 )            # sticky = 'n'


text1.grid(row=8, column=3, rowspan=2, columnspan=2, sticky = tk.NW, padx=10, pady=10)
label5.grid(row=8, column=5, rowspan=2, sticky = tk.NW, padx=10, pady=10)
#frame3.grid(row=8, column=10, columnspan=2)

root.mainloop()